package com.example.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backend.dto.BookDTO;
import com.example.backend.entity.Book;
import com.example.backend.mapper.BookMapper;
import com.example.backend.service.BookService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class BookServiceImpl implements BookService {
    
    private final BookMapper bookMapper;
    
    public BookServiceImpl(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }
    
    @Override
    public Page<BookDTO> page(Integer current, Integer size, String keyword) {
        Page<Book> page = new Page<>(current, size);
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(keyword)) {
            wrapper.like(Book::getName, keyword)
                  .or()
                  .like(Book::getAuthor, keyword)
                  .or()
                  .like(Book::getIsbn, keyword);
        }
        
        wrapper.orderByDesc(Book::getUpdateTime);
        
        Page<Book> bookPage = bookMapper.selectPage(page, wrapper);
        Page<BookDTO> bookDTOPage = new Page<>();
        BeanUtils.copyProperties(bookPage, bookDTOPage, "records");
        
        List<BookDTO> bookDTOList = bookPage.getRecords().stream().map(book -> {
            BookDTO bookDTO = new BookDTO();
            BeanUtils.copyProperties(book, bookDTO);
            return bookDTO;
        }).collect(Collectors.toList());
        
        bookDTOPage.setRecords(bookDTOList);
        return bookDTOPage;
    }
    
    @Override
    public BookDTO getById(Long id) {
        Book book = bookMapper.selectById(id);
        if (book == null) {
            throw new RuntimeException("图书不存在");
        }
        BookDTO bookDTO = new BookDTO();
        BeanUtils.copyProperties(book, bookDTO);
        return bookDTO;
    }
    
    @Override
    public void save(BookDTO bookDTO) {
        Book book = new Book();
        BeanUtils.copyProperties(bookDTO, book);
        bookMapper.insert(book);
    }
    
    @Override
    public void update(BookDTO bookDTO) {
        Book book = new Book();
        BeanUtils.copyProperties(bookDTO, book);
        bookMapper.updateById(book);
    }
    
    @Override
    public void delete(Long id) {
        bookMapper.deleteById(id);
    }
} 